import VConsole from 'vconsole'

// VConsole 实例
let vconsole = null

// 检查是否应该显示vConsole（开发环境始终显示，生产环境按用户权限）
function shouldShowVConsole() {
  try {
    // 开发环境始终显示vConsole
    if (import.meta.env.DEV) {
      return true
    }
    
    // 从localStorage获取用户信息
    const userStr = localStorage.getItem('user')
    if (!userStr) return false
    
    const user = JSON.parse(userStr)
    // 生产环境：只有指定用户才显示 VConsole
    return user?.username === '20108' || user?.username === '18013'
  } catch (error) {
    console.error('检查用户信息时出错:', error)
    return false
  }
}

// 增强的Network监控
let isNetworkPluginLoaded = false
function setupNetworkMonitoring() {
  if (!window.XMLHttpRequest || isNetworkPluginLoaded) return
  
  console.log('🔧 设置Network监控...')
  
  // 保存原始方法
  const originalXHR = window.XMLHttpRequest
  const originalFetch = window.fetch
  
  // 重写XMLHttpRequest
  if (originalXHR) {
    const XHR = function() {
      const xhr = new originalXHR()
      const startTime = Date.now()
      
      const originalOpen = xhr.open
      const originalSend = xhr.send
      
      xhr.open = function(method, url, async, user, password) {
        this._method = method
        this._url = url
        this._startTime = startTime
        return originalOpen.apply(this, arguments)
      }
      
      xhr.send = function(data) {
        this._requestData = data
        
        const originalOnReadyStateChange = this.onreadystatechange
        this.onreadystatechange = function() {
          if (this.readyState === 4) {
            const endTime = Date.now()
            const duration = endTime - this._startTime
          }
          
          if (originalOnReadyStateChange) {
            originalOnReadyStateChange.apply(this, arguments)
          }
        }
        
        return originalSend.apply(this, arguments)
      }
      
      return xhr
    }
    
    window.XMLHttpRequest = XHR
  }
  
  // 重写fetch
  if (originalFetch) {
    window.fetch = function(...args) {
      const startTime = Date.now()
      const [url, config] = args
      
      return originalFetch.apply(this, args).then(response => {
        const endTime = Date.now()
        const duration = endTime - startTime
        
        const clonedResponse = response.clone()
        clonedResponse.text().then(text => {
          console.log('🌐 Fetch请求:', {
            url: url,
            method: config?.method || 'GET',
            status: response.status,
            duration: duration + 'ms',
            response: text?.substring(0, 200)
          })
        })
        
        return response
      }).catch(error => {
        const endTime = Date.now()
        const duration = endTime - startTime
        
        console.log('🌐 Fetch错误:', {
          url: url,
          method: config?.method || 'GET',
          duration: duration + 'ms',
          error: error.message
        })
        
        throw error
      })
    }
  }
  
  isNetworkPluginLoaded = true
  console.log('✅ Network监控已设置')
}

// 强制启用Network面板
function forceEnableNetwork() {
  if (window.vConsole && window.vConsole.pluginList) {
    const networkPlugin = window.vConsole.pluginList.find(p => p.name === 'network')
    if (networkPlugin) {
      networkPlugin.isReady = true
      console.log('✅ Network插件已强制激活')
    }
  }
}

// 初始化 VConsole
function initVConsole() {
  if (shouldShowVConsole()) {
    if (!vconsole) {
      try {
        console.log('🚀 初始化vConsole...')
        
        setupNetworkMonitoring()
        
        vconsole = new VConsole({
          theme: 'dark',
          defaultPlugins: ['system', 'network', 'element', 'storage'],
          maxLogNumber: 1000,
          disableLogScrolling: false,
          onReady: function() {
            console.log('🎉 vConsole已准备就绪')
            
            setTimeout(() => {
              if (vconsole && vconsole.showTab) {
                vconsole.showTab('network')
                forceEnableNetwork()

              }
            }, 500)
          }
        })
        
        window.vConsoleInstance = vconsole
        console.log('✅ vConsole已启用，包含Network面板')
        
      } catch (error) {
        console.error('vConsole初始化失败:', error)
      }
    }
  } else if (vconsole) {
    vconsole.destroy()
    vconsole = null
    window.vConsoleInstance = null
    console.log('vConsole已禁用')
  }
}

// 监听 localStorage 变化（用户登录/登出时）
window.addEventListener('storage', function(e) {
  if (e.key === 'user') {
    initVConsole()
  }
})

// 监听自定义事件（同一页面内的登录状态变化）
window.addEventListener('userLoginStatusChanged', function() {
  initVConsole()
})

// 开发环境强制启用vConsole
if (import.meta.env.DEV) {
  console.log('🚀 开发环境，强制启用vConsole')
  // 延迟初始化，确保DOM加载完成
  setTimeout(() => {
    initVConsole()
  }, 100)
} else {
  // 生产环境按正常逻辑初始化
  initVConsole()
}

// 页面加载时初始化
initVConsole()


// 导出初始化函数，供其他模块调用
export { initVConsole }
export default vconsole